﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;

namespace SmartSpace.UI.Silverlight.Dynamic.Controls
{
    /// <summary>
    /// 截断字符串
    /// </summary>
    public class ToShortStringConventer : IValueConverter
    {
        #region IValueConverter Members

        /// <summary>
        /// 转换方法
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //默认截取长度
            int length = 20;
            string strValue = string.Empty;
            if (value != null)
            {
                //去除回车换行符
                strValue = value.ToString().Replace('\n', ' ');
                if (parameter != null)
                {
                    if (int.TryParse(parameter.ToString(), out length))
                    {
                        length = int.Parse(parameter.ToString());
                    }
                }

                string ellipsis = "...";
                if (strValue.Length > length + ellipsis.Length)
                {
                    return string.Format("{0}{1}", strValue.Substring(0, length), ellipsis);
                }
            }
            return strValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value.ToString();
        }

        #endregion
    }
}
